import time

from selenium.webdriver import Keys
from selenium.webdriver.common.by import By

from Case.python_ui.Common.basepage import Basepage
from Case.python_ui.Common.commontool import CommonTool
from Case.python_ui.PageLocate.admin_prod_mng_locator import AdminProdMngLocator


class AdminProdMngPages(Basepage):
    query_param = {
        "marketplace category": {
            "table": {
                "product name": "test",
            }
        }
    }

    assert_data = {
        "product category": {
            "thead": ["Sort", "Product Name", "URL", "Creator", "Creation Time", "Action"],
            "actions": ["Price Plan", "Edit", "Delete"]
        },
        "marketplace category": {
            "thead": ["Product Name", "Product Code", "Status", "Developer", "Advertising Display", "Creator Account", "Create Time", "Action"],
            "pup": {
                "add sub_menu success": "Marketplace category is created successfully.",
                "edit sub_menu success": "Marketplace category is edited successfully.",
                "delete sub_menu success": "Marketplace category is deleted successfully."
            }
        },
        "registration": {
            "thead": ["Request ID", "Company Name", "Account Type", "Amount", "Settlement Currency", "Account Email", "Phone Number", "Status", "Apply Time", "Approver", "Action"],
        },
        "marketplace product": {
            "thead": ["Product ID", "Product Name", "Company Name", "Applicant Account", "Type", "Status", "Created Time", "Approval Time", "Actions"]
        }
    }

    def enter_product_category_page(self):
        doc = '进入Product CateGory页面'
        for i in range(3):
            try:
                eles = self.get_elements(AdminProdMngLocator.default_page_expanded, doc)
                for ele in eles:
                    ele.click()
                    time.sleep(1)
                self.wait_elevisble(AdminProdMngLocator.product_management_tab, doc)
                self.click_element(AdminProdMngLocator.product_management_tab, doc)
                self.wait_elevisble(AdminProdMngLocator.product_category_tab, doc)
                self.click_element(AdminProdMngLocator.product_category_tab, doc)
                break
            except:
                self.refresh_page()
                continue
        time.sleep(5)

    def enter_marketplace_category_page(self):
        doc = '进入Marketplace CateGory页面'
        for i in range(3):
            try:
                eles = self.get_elements(AdminProdMngLocator.default_page_expanded, doc)
                for ele in eles:
                    ele.click()
                    time.sleep(1)
                self.wait_elevisble(AdminProdMngLocator.product_management_tab, doc)
                self.click_element(AdminProdMngLocator.product_management_tab, doc)
                self.wait_elevisble(AdminProdMngLocator.marketplace_category_tab, doc)
                self.click_element(AdminProdMngLocator.marketplace_category_tab, doc)
                break
            except:
                self.refresh_page()
                continue
        time.sleep(5)

    def prod_table_columns(self):
        doc = "检验Product Category页面列表字段"
        self.enter_product_category_page()

        thead_items = self.get_elements(AdminProdMngLocator.thead_items, doc)
        thead_names = self.assert_data["product category"]["thead"]

        for item in thead_items:
            if item.text != '':
                assert thead_names[thead_items.index(item)] in item.text

        table_actions = self.assert_data["product category"]["actions"]
        assert self.get_element(AdminProdMngLocator.product_category_table_actions_price_plan_button, doc).text == table_actions[0]
        self.move_mouse_to_click_element(AdminProdMngLocator.product_category_table_actions_ellipsis_button, doc)
        time.sleep(2)
        ellipsis_actions = self.get_elements(AdminProdMngLocator.product_category_table_ellipsis_actions, doc)
        assert table_actions[1] == ellipsis_actions[0].text
        assert table_actions[2] == ellipsis_actions[1].text

    def get_operation_name_click(self, operation):
        doc = '通过操作的名称去点击'
        eles = self.get_elements(AdminProdMngLocator.operation_type, doc)
        for ele in eles:
            if ele.text == operation:
                time.sleep(2)
                ele.click()

    def create_marketplace_category(self):
        marketplace_category_name = CommonTool.generate_string()
        doc = '创建市场类别'
        self.enter_marketplace_category_page()
        self.click_element(AdminProdMngLocator.category_add_button, doc)
        self.wait_elevisble(AdminProdMngLocator.level_menu_name_input, doc)
        self.send_keys(AdminProdMngLocator.level_menu_name_input, marketplace_category_name, doc)
        self.click_element(AdminProdMngLocator.public_confirm_button, doc)
        return marketplace_category_name

    def query_marketplace_category(self, marketplace_category_name):
        doc = '查询市场类别'
        self.keyboard_event(AdminProdMngLocator.category_name_input, doc)
        self.send_keys(AdminProdMngLocator.category_name_input, marketplace_category_name, doc)
        time.sleep(2)
        self.click_element(AdminProdMngLocator.category_query_button, doc)
        try:
            self.wait_elevisble(AdminProdMngLocator.market_category_list, doc)
            time.sleep(2)
            category_list = self.get_elements(AdminProdMngLocator.market_category_list, doc)
            category_list[0].click()
            return category_list
        except:
            pass

    def delete_marketplace_category(self, marketplace_category_name):
        doc = '删除市场类别'
        self.refresh_page()
        self.enter_marketplace_category_page()
        self.query_marketplace_category(marketplace_category_name)
        time.sleep(2)
        self.move_mouse_to_click_element(AdminProdMngLocator.market_category_action, doc)
        self.get_operation_name_click('Delete')
        self.wait_elevisble(AdminProdMngLocator.marketplace_confirm_button, doc)
        self.click_element(AdminProdMngLocator.marketplace_confirm_button, doc)
        self.wait_elevisble(AdminProdMngLocator.operation_prompt, doc)

    def mp_check_table_columns(self):
        doc = "检验Marketplace Category页面列表字段"
        self.enter_marketplace_category_page()

        thead_items = self.get_elements(AdminProdMngLocator.thead_items, doc)
        thead_names = self.assert_data["marketplace category"]["thead"]

        for item in thead_items:
            print(item.text)
            if item.text != '':
                assert thead_names[thead_items.index(item)] in item.text

    def mp_query_table(self):
        doc = "校验Marketplace Category页面列表查询功能"
        self.enter_marketplace_category_page()

        self.send_keys(AdminProdMngLocator.table_query_prodName_input, self.query_param["marketplace category"]["table"]["product name"], doc)
        time.sleep(1)
        self.click_element(AdminProdMngLocator.table_query_trigger_button, doc)
        time.sleep(3)
        prod_name_eles = self.get_elements(AdminProdMngLocator.table_row_first_col, doc)
        print(len(prod_name_eles))
        for ele in prod_name_eles:
            print(ele.text)
            assert self.query_param["marketplace category"]["table"]["product name"] in ele.text.lower()

    def mp_create_son_menu(self):
        doc = "创建子产品列表"
        self.enter_marketplace_category_page()
        self.move_mouse_to_click_element(AdminProdMngLocator.market_category_action, doc)
        self.get_operation_name_click('Add Sub-Menu')

        time.sleep(1)
        test_sub_menu_name = CommonTool.generate_string()

        self.send_keys(AdminProdMngLocator.layer_sub_menu_name_input, test_sub_menu_name, doc)
        self.click_element(AdminProdMngLocator.layer_sub_menu_save_button, doc)

        time.sleep(2)
        assert self.get_element(AdminProdMngLocator.success_pup, doc).text == self.assert_data["marketplace category"]["pup"]["add sub_menu success"]

        self.refresh_page()
        return test_sub_menu_name

    def mp_edit_son_menu(self, test_sub_menu_name):
        doc = "修改子产品列表名"
        test_sub_menu_xpath = f"//div[text()='{test_sub_menu_name}']"
        self.click_element((By.XPATH, test_sub_menu_xpath), doc)
        time.sleep(2)
        self.move_mouse_to_element(AdminProdMngLocator.actions_dropdown_button)

        self.get_operation_name_click('Edit Sub-Menu')

        self.wait_elevisble(AdminProdMngLocator.edit_sub_menu_name_input, doc)

        self.keyboard_event(AdminProdMngLocator.edit_sub_menu_name_input, doc)
        new_test_sub_menu_name = CommonTool.generate_string()
        self.send_keys(AdminProdMngLocator.edit_sub_menu_name_input, new_test_sub_menu_name, doc)
        self.click_element(AdminProdMngLocator.layer_sub_menu_save_button, doc)

        time.sleep(2)
        assert self.get_element(AdminProdMngLocator.success_pup, doc).text == self.assert_data["marketplace category"]["pup"]["edit sub_menu success"]

        self.refresh_page()
        return new_test_sub_menu_name

    def mp_delete_son_menu(self, sub_menu_name):
        doc = "删除子产品列表名"
        test_sub_menu_xpath = f"//div[text()='{sub_menu_name}']"
        self.click_element((By.XPATH, test_sub_menu_xpath), doc)
        time.sleep(2)
        self.move_mouse_to_element(AdminProdMngLocator.actions_dropdown_button)

        self.get_operation_name_click('Delete Sub-Menu')

        self.wait_elevisble(AdminProdMngLocator.delete_sub_menu_confirm_button, doc)

        self.click_element(AdminProdMngLocator.delete_sub_menu_confirm_button, doc)

        time.sleep(2)
        assert self.get_element(AdminProdMngLocator.success_pup, doc).text == self.assert_data["marketplace category"]["pup"]["delete sub_menu success"]

    def enter_approval_registration(self):
        doc = "进入Registration页面"
        self.click_element(AdminProdMngLocator.registration_tab, doc)
        self.wait_eleinvisble(AdminProdMngLocator.loading_anime, doc)

    def enter_approval_marketplace_product(self):
        doc = "进入Marketplace Product页面"
        self.click_element(AdminProdMngLocator.marketplace_product_tab, doc)
        self.wait_eleinvisble(AdminProdMngLocator.loading_anime, doc)

    def registration_check_col(self):
        doc = "校验Registration页面列表字段"
        self.enter_approval_registration()
        thead_items = self.get_elements(AdminProdMngLocator.registration_thead_items, doc)
        for ele in thead_items:
            assert self.assert_data["registration"]["thead"][thead_items.index(ele)] in ele.text

    def marketplace_product_check_col(self):
        doc = "校验Registration页面列表字段"
        self.enter_approval_marketplace_product()
        thead_items = self.get_elements(AdminProdMngLocator.marketplace_product_thead_items, doc)
        for ele in thead_items:
            print(ele.text)
            assert self.assert_data["marketplace product"]["thead"][thead_items.index(ele)] in ele.text

    def product_category_page_optimize(self):
        doc = "校验Product Category页面优化项"

        self.enter_product_category_page()
        self.move_mouse_to_element(AdminProdMngLocator.product_category_table_actions_ellipsis_button)
        time.sleep(1)
        self.get_elements(AdminProdMngLocator.product_category_table_ellipsis_actions, doc)[0].click()
        # 去掉Display Resource Flag
        time.sleep(2)
        edit_drawer_items = self.get_elements(AdminProdMngLocator.product_category_edit_drawer_item, doc)
        item_list = [item.text for item in edit_drawer_items]
        print(item_list)
        assert "Display Resource Flag:" not in item_list
        # 新增free product字段
        assert "Free Product" in item_list
        # 修改 Product console URL Type和Product console URL
        assert "Product console URL Type:" in item_list
        assert "Product console URL:" in item_list

    def select_text_within_element(self, element, start, end):
        js_code = """
            function selectText(element, start, end) {
                var range = document.createRange();
                var selection = window.getSelection();

                range.setStart(element.firstChild, start);
                range.setEnd(element.firstChild, end);

                selection.removeAllRanges();
                selection.addRange(range);
            }

            selectText(arguments[0], arguments[1], arguments[2]);
        """

        self.driver.execute_script(js_code, element, start, end)

    def insert_link_by_str(self, element, father_str, sub_str, link):
        doc = "编辑文字链接"
        start_index = father_str.find(sub_str)
        end_index = start_index + len(sub_str)
        self.select_text_within_element(element, start_index, end_index)
        time.sleep(1)
        self.click_element(AdminProdMngLocator.insert_link_button, doc)
        time.sleep(1)
        self.send_keys(AdminProdMngLocator.link_source_input, link, doc)
        time.sleep(1)
        self.click_element(AdminProdMngLocator.insert_link_confirm, doc)
        time.sleep(1)

    def query_product_category_list(self, list_name):
        doc = f"点击{list_name}List tab"
        list_xpath = f"//span[text()='{list_name}']/.."
        self.click_element((By.XPATH, list_xpath), doc)
        time.sleep(1)

    def query_product_category(self, category_name):
        doc = f"查询{category_name}类别"
        self.send_keys(AdminProdMngLocator.table_query_prodName_input, category_name, doc)
        time.sleep(1)
        self.click_element(AdminProdMngLocator.table_query_trigger_button, doc)
        time.sleep(3)

    def product_category_edit_config_term(self):
        doc = "配置Product Category产品购买协议"
        self.enter_product_category_page()
        self.query_product_category_list("Computing")
        self.query_product_category("ApiGateway")

        self.move_mouse_to_element(AdminProdMngLocator.product_category_table_actions_ellipsis_button)
        time.sleep(1)
        self.get_elements(AdminProdMngLocator.product_category_table_ellipsis_actions, doc)[0].click()
        time.sleep(2)
        terms_of_service_str = "I have read and agree to Product Terms of Service and Special Offers Terms."
        self.keyboard_event(AdminProdMngLocator.terms_of_service_input, doc)
        time.sleep(1)
        self.move_mouse_to_click_element(AdminProdMngLocator.terms_of_service_input, doc)
        time.sleep(1)
        # 选中文字
        self.send_keys(AdminProdMngLocator.terms_of_service_input, terms_of_service_str, doc)
        text_element_1 = self.get_element((By.XPATH, "//span[@data-slate-string]"), doc)
        select_text_1 = "Product Terms of Service"
        link_str_1 = "http://testcreadmin.aligy.cn/console/product/category"
        self.insert_link_by_str(text_element_1, terms_of_service_str, select_text_1, link_str_1)
        text_element_2 = self.get_elements((By.XPATH, "//span[@data-slate-string]"), doc)[2]
        select_text_2 = "Special Offers Terms"
        link_str_2 = "http://testcreadmin.aligy.cn/console/product/category"
        self.insert_link_by_str(text_element_2, text_element_2.text, select_text_2, link_str_2)
        time.sleep(1)
        self.click_element(AdminProdMngLocator.edit_drawer_confirm, doc)
        self.wait_elevisble(AdminProdMngLocator.success_pup, doc)
        success_pup = self.get_element(AdminProdMngLocator.success_pup, doc)
        assert success_pup.text == "Edited successfully."


